# Please note that modules are singletons, the init code will not happen multiple times
import sys
if sys.version_info[0] == 2:
    from ConfigParser import SafeConfigParser
else:
    from configparser import SafeConfigParser
import atexit
import os

from .functions import ( int_to_twos, twos_to_int, sign_extend )

# constants (may get their own file if there are sufficiently many)
DATA_ADDRESS = 0x10000000
TEXT_ADDRESS = 0x00400000

REG_NAMES = ['zero', 'at', 'v0', 'v1', 'a0', 'a1', 'a2', 'a3', 't0', 't1',
            't2', 't3', 't4', 't5', 't6', 't7', 's0', 's1', 's2', 's3',
            's4', 's5', 's6', 's7', 't8', 't9', 'k0', 'k1', 'gp', 'sp',
            'fp', 'ra']

# most non-config-related functions have their own file

def deprecated(f):
    def _f(*a, **kw):
        if config.getboolean('global','debug'):
            from warnings import warn
            warn(str(f), DeprecationWarning)
        return f(*a,**kw)
    return _f

def verbose_print(*text):
    if config.getboolean('global', 'verbose'):
        sys.stdout.write(' '.join([str(t) for t in text]) + '\n')

def debug_print(*text):
    if config.getboolean('global', 'debug'):
        sys.stderr.write(' '.join([str(t) for t in text]) + '\n')


def save_config(name=None):
    name = conf_file if name is None else name
    with open(name, 'w') as f:
        config.write(f)

# initialize the config

config = SafeConfigParser()

conf_dir = os.path.expanduser('~/.moops')

if not os.path.exists(conf_dir):
    os.mkdir(conf_dir)

# TODO: eventually, this should be overridable via a switch
conf_file = os.path.join(conf_dir, 'moops.cfg')

if not os.path.exists(conf_file):
    sys.stdout.write("No config file found, writing default to %s\n" % conf_file)
    config.add_section('global')
    config.set('global', 'debug', 'false')
    config.set('global', 'verbose', 'false')
    config.set('global','ui', 'Qt')
    config.add_section('web_ui')
    config.set('web_ui', 'host', 'localhost')
    config.set('web_ui', 'port', '8080')
    config.add_section('qt_ui')

    save_config()

else:
    config.read(conf_file)



